package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("user:{}", user);
        //获取手机号
        String phone = user.getPhone();

        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            throw new CustomException("手机号不能为空");
        }

        //生成随机验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("code:{}", code);

        //发送短信验证码
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code.toString());

        //将验证码以key=phone;value=code的型式存入session中
//        session.setAttribute(phone, code);

        //往redis里存验证码
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        //后期会用redis优化session缓存时间
        //session.setMaxInactiveInterval(60);
        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //接收前端发送的请求中的JSON中的数据
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone).toString();
        //获取session中的数据
//        Object codeInSession = session.getAttribute(phone).toString();
        //对比验证码是否正确
        if (code != null && codeInSession.equals(code)) {

            //结果相等,验证码正确,判断是否第一次登录,如果是,则注册,如果不是则登录
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);

            //如果是null,则证明需要注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
//            session.removeAttribute(phone);
            //从Redis中删除缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("已退出登录");
    }
}
